package com.xunmall.web.controller;

import com.xunmall.base.dto.Result;
import com.xunmall.web.entity.UserDO;
import com.xunmall.web.model.PageResult;
import com.xunmall.web.model.vo.UserVO;
import com.xunmall.web.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/system/user")
public class SystemUserWebController extends BaseWebController {

    @Autowired
    private UserService userService;

    private String viewPath = "system/user/";

    @RequestMapping("/list")
    public ModelAndView listPage(@ModelAttribute UserVO userVO) {
        ModelAndView mv = new ModelAndView();
        PageResult pageResult = userService.findUserListByCondition(userVO);
        mv.setViewName(viewPath + "list");
        mv.addObject("pageResult", pageResult);
        return mv;
    }

    @RequestMapping(value = "/add_page")
    public String addPage() {
        return viewPath + "add";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Object add(UserDO userDO) {
        Result result = userService.saveUser(userDO);
        if (result.getSuccess()) {
            return jsonReturn(200);
        } else {
            return jsonReturn(300, result.getMessage());
        }
    }

    @RequestMapping(value = "/edit")
    public String edit(@RequestParam("uuid") String uuid, HttpServletRequest request) {
        Result result = userService.findUserById(uuid);
        request.setAttribute("user", result.getData());
        return viewPath + "edit";
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object update(UserDO userDO) {
        Result result = userService.updateUser(userDO);
        if (result.getSuccess()) {
            return jsonReturn(200);
        } else {
            return jsonReturn(300, result.getMessage());
        }
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public Object delete(@RequestParam("uuid") String uuid) {
        Result result = userService.deleteUserById(uuid);
        if (result.getSuccess()) {
            return jsonReturn(200,false);
        } else {
            return jsonReturn(300, result.getMessage(),false);
        }
    }

}